package com.servicesystem.servicesystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.servicesystem.servicesystem.entity.AliGoodsLib;
import com.servicesystem.servicesystem.entity.AliTtGoods;
import com.servicesystem.servicesystem.entity.TtOrder;
import com.servicesystem.servicesystem.service.AliGoodsLibService;
import com.servicesystem.servicesystem.service.AliTtGoodsService;
import com.servicesystem.servicesystem.service.TtOrderService;
import com.servicesystem.servicesystem.untis.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * (AliGoodsLib)表控制层
 *
 * @author makejava
 * @since 2020-09-09 16:11:36
 */
@RestController
@RequestMapping("aliGoodsLib")
public class AliGoodsLibController {
    /**
     * 服务对象
     */
    @Resource
    private AliGoodsLibService aliGoodsLibService;
    @Autowired
    private TtOrderService ttOrderService;
    @Autowired
    private AliTtGoodsService aliTtGoodsService;

    @GetMapping("get-goods/{current}")
    public R getAliGoods(@PathVariable(value = "current") Long current) {
        Page<AliGoodsLib> aliGoodsLibPage = new Page<>(current, 16);
        QueryWrapper<AliGoodsLib> aliGoodsLibQueryWrapper = new QueryWrapper<>();
        Page<AliGoodsLib> page = aliGoodsLibService.page(aliGoodsLibPage, aliGoodsLibQueryWrapper);
        return R.success(page);
    }

    @GetMapping("get-goods/by-id/{id}")
    public R getAliGoodsById(@PathVariable(value = "id") String id) {
        AliGoodsLib aliGoodsLib = aliGoodsLibService.getById(id);
        return R.success().data(aliGoodsLib);
    }

    @DeleteMapping("delete-goods/{id}")
    public R deleteGoods(@PathVariable("id") String id) {
        AliGoodsLib byId = aliGoodsLibService.getById(id);
        Optional.ofNullable(byId).ifPresent(item -> {
            QueryWrapper<AliTtGoods> aliTtGoodsQueryWrapper = new QueryWrapper<>();
            aliTtGoodsQueryWrapper.eq("offer_id", item.getOfferId());
            aliTtGoodsService.remove(aliTtGoodsQueryWrapper);
            aliGoodsLibService.removeById(id);
        });
        return R.fail("失败");
    }

    @PostMapping("add-tt-order/by-web")
    public R addGoods(@RequestBody TtOrder ttOrder) {
        ttOrderService.save(ttOrder);
        return R.success();
    }
}
